package top.blackr.folivora.common.notification;

import cn.hutool.core.util.ObjectUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class NotificationAspect {

    private final NotificationFactory notificationFactory;

    @Around("@annotation(notification)")
    public Object doAround(ProceedingJoinPoint point, Notification notification) throws Throwable {
        // 先用环绕，方便后续扩展
        Object result = point.proceed();
        // 异步发送消息
        sendNotification(notification);
        return result;
    }

    /**
     * 异步发送消息
     *
     * @param notification 消息内容
     */
    @Async
    public void sendNotification(Notification notification) {
        assert ObjectUtil.isNotEmpty(notification.type()) :  "消息发送失败，消息类型为空";
        assert ObjectUtil.isNotEmpty(notification.target()) :  "消息发送失败，接收人为空";
        notificationFactory.getNotification(notification.type()).send(new NotificationConfig()
                .setContent(notification.content())
                .setTitle(notification.title())
                .setTarget(notification.target()));
    }
}
